import csv


def grid_polygons(n=3):
    lat_min, lat_max = -90, 90
    lon_min, lon_max = -180, 180
    rows = cols = 2 ** 8
    lat_step = (lat_max - lat_min) / rows
    lon_step = (lon_max - lon_min) / cols

    polygons = []
    for i in range(rows):
        for j in range(cols):
            min_lat = lat_min + i * lat_step
            max_lat = min_lat + lat_step
            min_lon = lon_min + j * lon_step
            max_lon = min_lon + lon_step
            # WKT Polygon: POLYGON((x1 y1, x2 y2, x3 y3, x4 y4, x1 y1))
            wkt = (
                f"POLYGON(({min_lon} {min_lat}, {max_lon} {min_lat}, "
                f"{max_lon} {max_lat}, {min_lon} {max_lat}, {min_lon} {min_lat}))"
            )
            name = f"grid_{i}_{j}"
            polygons.append((wkt, name))
    return polygons


def write_csv(filename, polygons):
    with open(filename, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['geom', 'name'])
        for wkt, name in polygons:
            writer.writerow([wkt, name])


if __name__ == "__main__":
    polygons = grid_polygons(n=3)
    write_csv('global_grid.csv', polygons)
    print("CSV文件已生成，共写入", len(polygons), "个网格。")
